import React, { useEffect, useRef, useState } from 'react';
import { Button, Col, Form, Input, Modal, Row, Switch, Tree, TreeSelect, message, Space, Dropdown, MenuProps, FormProps, InputRef, App, AutoComplete, Select, Empty } from 'antd';
import { addDepartment, addPosRoleType, addPosition, addRole, addUser, delAllRole, delDepartment, delPosRoleType, delPosition, delRole, deleteUser, deleteUserList, editDepartment, editPosition, editRole, editUser, edutPosRoleType, getAcountList, getAllPositionList, getDepartTree, getPositionList, getPositionTree, getRoleList, toggleRole } from '@/services/demo/UserController';
import "./index.less";
import { ActionType, ProCard, ProTable } from '@ant-design/pro-components';
import Empower from '@/components/Empower';
import { uuid } from '@/utils/format';
import { RoleCode } from "@/../../code";
import { useModel } from '@umijs/max';
import AuthButton from "@/components/AuthButton";
interface DepartItem {
  title: string,
  parentId: string,
  id: string,
  children: DepartItem[];
}
interface OptionType {
  label: string,
  key: string,
  value?: string;
  code?: string;
}
const items: OptionType[] = [
  {
    label: '编辑',
    key: '1',
    code: RoleCode["BTN_MENU_EDIT"]
  },
  {
    label: '添加类别',
    key: '2',
    code: RoleCode["BTN_ADD_MENU_CLASSIFY"]
  },
  {
    label: '添加子类别',
    key: '3',
    code: RoleCode["BTN_ADD_MENU_CHILD_CLASSIFY"]
  },
  {
    label: '删除',
    key: '4',
    code: RoleCode["BTN_MENU_DEL"]
  },
];

export default function Page() {
  const emRef = useRef<{ finish: any; }>();
  const [positionOptions, setPositionOptions] = useState<OptionType[]>([]);
  const [optionType, setOptionType] = useState<OptionType>({ key: "", label: "" });
  const [menuLoading, setMenuLoading] = useState(true);
  const [selectedTreeKeys, setSelectedTreeKeys] = useState<React.Key[]>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [model, contextHolder] = Modal.useModal();
  const tableRef = useRef<ActionType>();
  const inputRef = useRef<InputRef | null>(null);
  const [form] = Form.useForm();
  const [treeForm] = Form.useForm();
  const [tableParams, setTableParams] = useState<{ typeId?: string, roleName?: string; }>({});
  const [typeData, setTypeData] = useState([]);
  const [positionType, setPositionType] = useState<string>();
  const [modalType, setModalType] = useState("新增");
  const [initialValues, setInitialValues] = useState({ status: 1 });
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isOptionModalOpen, setIsOptionModalOpen] = useState(false);
  const { initialState: { elements } } = useModel('@@initialState') as any;

  const columns: any[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 80,
    },
    {
      title: '角色类别',
      dataIndex: 'typeId',
      key: "typeId",
      search: false
    },
    {
      title: '角色编码',
      dataIndex: 'code',
      search: false,
    },
    {
      title: '角色名称',
      dataIndex: 'roleName',
      search: true
    },
    {
      title: '状态',
      dataIndex: 'status',
      search: false,
      render: (text: number, row: { id: string; }) => <Switch disabled={!elements.includes(RoleCode['BTN_STATUS'])} onChange={() => toggleRole(row.id)
      } defaultChecked={Boolean(text)} />
    },
    {
      title: '关联岗位数量',
      dataIndex: 'postCount',
      search: false
    },
    {
      title: '创建人',
      dataIndex: 'createName',
      search: false
    },
    {
      title: '创建时间',
      dataIndex: 'createTIme',
      search: false,
      valueType: "dateTime"
    },
    {
      title: '操作',
      fixed: 'right',
      search: false,
      render: (user: API.AddPosition) => {

        return [
          <Button key="detail" size='small' type='link' onClick={() => accountDetail(user)}>详情</Button>,
          <AuthButton key="edit" size='small' type='link' permission={RoleCode['BTN_EDIT']} onClick={() => accountEdit(user)}>编辑</AuthButton>,
          <AuthButton key="delete" size='small' type='link' danger permission={RoleCode['BTN_DEL']} onClick={() => accountDelete(user.id!)}>删除</AuthButton>
        ];
      },
    },
  ];

  useEffect(() => {
    reloadDepartmentTree();

    getAllPositionList().then(res => {
      if (res.success) {
        const options = res.result.map((data: { postName: string, id: string; }) => ({ value: data.id, label: data.postName }));
        console.log(options);

        setPositionOptions(options);
      }
    });
  }, []);
  const selectChange = (keys: React.Key[]) => {
    setSelectedRowKeys(keys);
  };
  const onFinish = async () => {
    const params = { ...form.getFieldsValue(), ...emRef.current?.finish() };

    let data;
    let text;
    if (modalType == "新增") {
      data = await addRole(params);
      text = "新增角色成功";
    } else if (modalType == "编辑") {
      data = await editRole(params);
      text = "编辑角色成功";
    }
    const { success } = data;
    if (success) {
      (!tableParams.typeId || (form.getFieldValue("typeId") == tableParams.typeId)) && tableRef.current?.reload();
      setIsModalOpen(false);
      message.success(text);
    }
  };

  const reloadDepartmentTree = () => {
    getPositionTree(1).then(res => {
      if (res.success) {
        setTypeData(res.result);
        setMenuLoading(false);
      }
    });

  };
  const handlePosition = (newValue: string) => {
    setPositionType(newValue);

  };

  const onMenuSelect = (ids: React.Key[]) => {
    setSelectedTreeKeys(ids);
    const deepTableParams = JSON.parse(JSON.stringify(tableParams));
    deepTableParams.typeId = ids[0];
    setTableParams(deepTableParams);
  };
  const handleSubmit = () => {
    form.submit();
  };

  const accountAdd = () => {
    setIsModalOpen(true);
    setModalType("新增");
    form.resetFields();
    form.setFieldValue("code", uuid());
  };
  const accountEdit = (user: API.AddPosition) => {
    setIsModalOpen(true);
    form.setFieldsValue(user);
    setModalType("编辑");
  };
  const accountDetail = (user: API.AddPosition) => {
    setIsModalOpen(true);
    form.setFieldsValue(user);
    setModalType("详情");

  };
  const delAccountList = () => {
    if (selectedRowKeys.length) {
      console.log(selectedRowKeys);
      delAllRole(selectedRowKeys).then(res => {
        if (res.success) {
          message.success("批量删除成功");
          tableRef.current?.reload();
        }
      });
    } else {
      message.warning("请选中要删除的角色列表");
    }
  };
  const accountDelete = async (id: string) => {

    const confirmed = await model.confirm({ content: "确定删除?" });
    if (confirmed) {
      delRole(id).then(res => {
        if (res.success) {
          message.success("删除成功");
          tableRef.current?.reload();
        }
      });
    }
  };

  const menuClick = async (e: any, dataNode: DepartItem) => {
    e.domEvent.stopPropagation();
    console.log(dataNode);

    if (e.key === "4") {
      const confirmed = await model.confirm({ content: dataNode.title + " -> " + "确定删除?" });

      if (confirmed) {
        delPosRoleType(dataNode.id).then(res => {
          if (res.success) {
            message.success("删除成功");
            reloadDepartmentTree();
          }
        });
      }
    } else {
      setIsOptionModalOpen(true);
      setOptionType({ label: dataNode.title + " -> " + (items![e.key - 1] as any).label, key: e.key });

      ["2", "3"].includes(e.key) && treeForm.resetFields();
      e.key === "1" && treeForm.setFieldValue("typeName", dataNode.title);
      treeForm.setFieldValue("parentId", e.key === "2" ? dataNode.parentId : dataNode.id);
    }
  };
  useEffect(() => {
    if (isOptionModalOpen) {
      setTimeout(() => {
        inputRef.current?.focus();
      }, 0);
    }
  }, [isOptionModalOpen]);

  const onTreeFinished = async () => {
    console.log(treeForm.getFieldsValue(), optionType);
    const deepData = treeForm.getFieldsValue();
    const findItem = items?.find(item => item?.key === optionType.key);
    if (!findItem) return;
    let data;
    if (["2", "3"].includes(optionType.key)) {
      data = await addPosRoleType(deepData);
    } else {

      deepData.id = deepData.parentId;
      delete deepData.parentId;
      console.log(deepData);

      data = await edutPosRoleType(deepData);
    }

    if (data.success) {
      message.success(findItem.label + "成功");
      reloadDepartmentTree();
      if (findItem.key === "1" && tableParams.typeId === deepData.id) {
        tableRef.current?.reload();
      }
    } else {
      message.error(findItem.label + "是啊比");
    }

    setIsOptionModalOpen(false);
  };

  return (
    <div>
      <ProCard split="vertical" style={{ height: "calc(100vh - 176px)" }}>
        <ProCard headerBordered loading={menuLoading} colSpan="20%" style={{ height: "100%", overflowY: "auto" }}>
          <Tree
            onSelect={onMenuSelect}
            fieldNames={{ title: "title", key: "id", children: "children" }}
            treeData={typeData}
            selectedKeys={selectedTreeKeys}
            titleRender={(dataNode: any) => <Dropdown menu={{ items: items.filter(item => elements.includes(item.code)), onClick: (e) => menuClick(e, dataNode) }} trigger={['contextMenu']}><div>{dataNode.title}</div></Dropdown>
            }
          />
        </ProCard>
        <ProCard headerBordered colSpan="80%" style={{ height: "100%", overflowY: "auto" }}>
          <ProTable
            actionRef={tableRef}
            cardBordered
            options={false}
            headerTitle={<Space style={{ marginBottom: "20px" }}>
              <AuthButton type='primary' permission={RoleCode['BTN_ADD']} onClick={accountAdd}>新增</AuthButton>
              <AuthButton permission={RoleCode['BTN_ALL_DEL']} onClick={delAccountList}>批量删除</AuthButton>
            </Space>}
            params={tableParams}
            request={async (params) => {
              const { current, pageSize, typeId, roleName } = params;
              const { success, result: { datas, total } } = await getRoleList({ page: current!, size: pageSize!, param: { typeId, roleName } });

              return { data: datas, total, success };
            }}

            columns={columns}
            rowKey="id"
            rowSelection={{ selectedRowKeys, onChange: selectChange }}
          />
        </ProCard>
      </ProCard>


      <Modal title={optionType.label} maskClosable={false} open={isOptionModalOpen} onOk={() => treeForm.submit()} onCancel={() => setIsOptionModalOpen(false)} okText="提交">
        <Form form={treeForm} initialValues={{ plat: 1 }} onFinish={onTreeFinished}>
          <Form.Item
            name="parentId"
            hidden
            rules={[{ required: true, message: '无父节点id' }]}>
            <Input />
          </Form.Item>
          <Form.Item
            name="plat"
            hidden>
            <Input />
          </Form.Item>
          <Form.Item label="角色类别"
            name="typeName"
            rules={[{ required: true, message: '请输入角色类别' }]}>
            <Input ref={inputRef} showCount allowClear placeholder='请输入角色类别' maxLength={20} />
          </Form.Item>
        </Form>
      </Modal>

      <Modal width="1200px" footer={(dom: React.ReactNode) => modalType == "详情" ? null : dom} className='account_modal' title={`角色 - ${modalType}`} maskClosable={false} open={isModalOpen} onOk={handleSubmit} onCancel={() => setIsModalOpen(false)} okText="提交"  >
        <Form size='large' labelCol={{ span: 4 }} form={form} disabled={modalType === "详情"} initialValues={initialValues} onFinish={onFinish}>
          <Form.Item
            name="id"
            hidden
          >
            <Input />
          </Form.Item>
          <Form.Item label="角色类别"
            name="typeId"
            rules={[{ required: true, message: '请输入角色类别' }]}
          >
            <TreeSelect
              showSearch
              value={positionType}
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              placeholder="请选择角色类别"
              allowClear
              treeDefaultExpandAll
              onChange={handlePosition}
              treeData={typeData}
              fieldNames={{ label: "title", value: "id", children: "children" }}
            />

          </Form.Item>
          <Form.Item
            label="角色编码"
            name="code"
            rules={[{ required: true, message: '请输入唯一角色编码' }]}
          >
            <Input disabled={modalType === "编辑"} allowClear placeholder='请输入唯一岗位编码' maxLength={30} showCount />
          </Form.Item>
          <Form.Item label="角色名称"
            name="roleName"
            rules={[{ required: true, message: '请输入角色名称' }]}
          >
            <Input placeholder="请输入角色名称" allowClear maxLength={30} showCount />
          </Form.Item>
          <Form.Item label="关联岗位"
            name="postIds"
            rules={[{ required: true, message: '请输入关联岗位（多选）' }]}
          >
            <Select
              mode="multiple"
              placeholder="请输入关联岗位（多选）"
              options={positionOptions}
              optionFilterProp="label"
            />
          </Form.Item>

          <Form.Item
            label="启用"
            name="status"
          >
            <Switch onChange={(val) => form.setFieldValue("status", Number(val))} />
          </Form.Item>
          <Form.Item
            label="授权项"
            dependencies={["id"]}
            style={{ width: "100%" }}
            labelCol={{ span: 2 }}
          >
            {() =>
              <Empower ref={emRef} disabled={modalType === "详情"} type='basic' role={form.getFieldValue("id")}></Empower>
            }

          </Form.Item>
          <Form.Item
            label="备注"
            name="remark"
            style={{ width: "100%" }}
            labelCol={{ span: 2 }}
          >
            <Input.TextArea placeholder='请输入备注' allowClear autoSize={{ minRows: 3 }} showCount maxLength={500} />
          </Form.Item>
        </Form>
      </Modal>
      {contextHolder}
    </div>
  );
}
